package com.wwwarehouse.usercenter.fragment.business_relationship;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CardDeskTaskResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.time_pick.ChoosePickerDialog;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.ImageloaderUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.bean.business_relationship.BRInviteFriendsBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.ContentValues.TAG;

/**
 * 业务伙伴邀请
 * Created by xiaoke.ni on 2017/10/21.
 */

@Route(path = UserCenterConstant.PATH_AUTHORITY_BR_INVITE_FRIENDS)
public class BRInviteFriendsFragment extends BaseFragment implements View.OnClickListener {

    private View mView;
    private ImageView mIconIv;//公司图标
    private TextView mCompanyTv;//公司
    private TextView mEtCompanyPhoneTv;//公司电话
    private TextView mNameTv;
    private TextView mCallTv;
    private ImageView mPhoneIv;
    private TextView mAddressTv;
    private TextView mAddressDetailTv;
    private Button mTurnDownBtn;
    private Button mFinishBtn;
    private RelativeLayout mBusinessRl;
    private TextView mBusinessSelectTv;
    private TextView mBusinessTv;
    private TextView mContentTitleTv;

    private BRInviteFriendsBean bean;
    private int invitedBuId;
    private String isAgree;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = View.inflate(getActivity(), R.layout.fragment_br_invite_friends, null);
        return mView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initEvent();
    }

    private void initView() {
        mIconIv = (ImageView) mView.findViewById(R.id.icon_iv);
        mCompanyTv = (TextView) mView.findViewById(R.id.company_tv);
        mEtCompanyPhoneTv = (TextView) mView.findViewById(R.id.et_company_phone_tv);
        mNameTv = (TextView) mView.findViewById(R.id.name_tv);
        mCallTv = (TextView) mView.findViewById(R.id.call_tv);
        mPhoneIv = (ImageView) mView.findViewById(R.id.phone_iv);
        mAddressTv = (TextView) mView.findViewById(R.id.address_tv);
        mAddressDetailTv = (TextView) mView.findViewById(R.id.address_detail_tv);
        mTurnDownBtn = (Button) mView.findViewById(R.id.turn_down_btn);
        mFinishBtn = (Button) mView.findViewById(R.id.finish_btn);
        mBusinessRl = (RelativeLayout) mView.findViewById(R.id.business_rl);
        mBusinessSelectTv = (TextView) mView.findViewById(R.id.business_select_tv);
        mBusinessTv = (TextView) mView.findViewById(R.id.business_tv);
        mContentTitleTv = (TextView) mView.findViewById(R.id.content_title_tv);
    }

    private void initEvent() {
        mCallTv.setOnClickListener(this);
        mPhoneIv.setOnClickListener(this);
        mBusinessRl.setOnClickListener(this);
        mTurnDownBtn.setOnClickListener(this);
        mFinishBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.call_tv || id == R.id.phone_iv) {
            if (bean == null)
                return;
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + bean.getInviterUserContact()));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }  else if (id == R.id.business_rl) {
            if (bean == null)
                return;
            final Map<String,Integer> map = new HashMap<>();
            List<String> list = new ArrayList<>();
            for (BRInviteFriendsBean.BuIdsBean buIdsBean : bean.getBuIds()){
                map.put(buIdsBean.getBuName(),buIdsBean.getBuId());
                list.add(buIdsBean.getBuName());
            }
            new ChoosePickerDialog.Builder(mActivity).setData(list).setTitle(getString(R.string.user_br_select_screen)).setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
                @Override
                public void onSelected(String itemValue, int position) {
                    mBusinessSelectTv.setText(itemValue);
                    invitedBuId = map.get(itemValue);
                    mFinishBtn.setBackground(getResources().getDrawable(R.drawable.common_btn1_normal_shape));
                    mFinishBtn.setEnabled(true);
                }

                @Override
                public void onCancel() {

                }
            }).create().show();
        } else if (id == R.id.turn_down_btn) {
            if (bean == null)
                return;
            DialogTools.getInstance().showTCDialog(getActivity(), getString(R.string.user_br_hint),
                    getString(R.string.user_br_sure_refused) + "" + getString(R.string.user_br_their_quest_establish_invitation), getString(R.string.user_br_sure_refused_1), getString(R.string.user_br_think),
                    new DialogTools.ConfirmListener() {
                        @Override
                        public void setConfirmListener(Dialog dialog, View view, String s) {
                            isAgree = "REFUSE";
                            inviteResult();
                            dialog.dismiss();
                        }
                    }, new DialogTools.DismissListener() {
                        @Override
                        public void setDismissListener(Dialog dialog, View view) {
                            dialog.dismiss();
                        }
                    });
        } else if (id == R.id.finish_btn) {
            if (bean == null)
                return;
            isAgree = "AGRESS";
            inviteResult();
        }

    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof BRInviteFriendsFragment) {
            mActivity.setTitle(getString(R.string.user_br_invite_frends));
        }
    }

    @Override
    public void requestDatas() {
        getInviteInfo();
    }

    /**
     *  请求任务卡片数据
     */
    private void getInviteInfo() {
        CardDeskTaskResponseBean.TaskBean taskBean = (CardDeskTaskResponseBean.TaskBean) getArguments().getSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS);
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("taskId", taskBean.getCardUkid());
        NoHttpUtils.httpPost(UserCenterConstant.GET_INVITE_INFO, hashMap, onResponseListener, 0);
        showProgressDialog();
    }

    /**
     *  邀请反馈
     */
    private void inviteResult() {
        CardDeskTaskResponseBean.TaskBean taskBean = (CardDeskTaskResponseBean.TaskBean) getArguments().getSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS);
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("invitedBuId", invitedBuId);
        hashMap.put("isAgree", isAgree);
        hashMap.put("taskId", taskBean.getCardUkid());
        NoHttpUtils.httpPost(UserCenterConstant.INVITE_RESULT, hashMap, onResponseListener, 1);
        showProgressDialog();
    }

    NoHttpUtils.OnResponseListener onResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case 0:
                    if (TextUtils.equals("0", commonClass.getCode())) {
                        bean = JSON.parseObject(commonClass.getData().toString(),BRInviteFriendsBean.class);
                        ImageloaderUtils.displayCircleImage(bean.getInviterBuLogoUrl(), mIconIv);
                        mCompanyTv.setText(bean.getInviterBuName());
                        String phone = bean.getInviterBuContact();
                        if (bean.getInviterBuContact().length() == 11){
                            phone = bean.getInviterBuContact().substring(0,3) + "-" + bean.getInviterBuContact().substring(3,7) + "-" + bean.getInviterBuContact().substring(7);
                        }else if (bean.getInviterBuContact().length() == 12){
                            phone = bean.getInviterBuContact().substring(0,4) + "-" + bean.getInviterBuContact().substring(4);
                        }
                        mEtCompanyPhoneTv.setText(phone);
                        mNameTv.setText(bean.getInviterUserName());
//                        mCallTv.setText(bean.getInviterUserContact());
                        mAddressTv.setText(bean.getInviterBuProvince() + bean.getInviterBuCity());
                        String address = "";
                        if (!TextUtils.isEmpty(bean.getInviterBuArea()))
                            address += bean.getInviterBuArea();
                        if (!TextUtils.isEmpty(bean.getInviterBuStreet()))
                            address += bean.getInviterBuStreet();
                        if (!TextUtils.isEmpty(bean.getInviterBuAddress()))
                            address += bean.getInviterBuAddress();
                        mAddressDetailTv.setText(address);
                        if (bean.getBuIds().size() >1){
                            mBusinessRl.setVisibility(View.VISIBLE);
                            mBusinessTv.setVisibility(View.GONE);
                            mFinishBtn.setBackground(getResources().getDrawable(R.drawable.common_btn1_noclick_shape));
                            mFinishBtn.setEnabled(false);
                        }else {
                            mBusinessTv.setText(getString(R.string.user_br_my_unit) + bean.getBuIds().get(0).getBuName());
                            invitedBuId = bean.getBuIds().get(0).getBuId();
                            mBusinessRl.setVisibility(View.GONE);
                            mBusinessTv.setVisibility(View.VISIBLE);
                        }
                        if (getString(R.string.br_customer).equals(bean.getInviteType())){
                            mContentTitleTv.setText(getString(R.string.user_br_invite_you_become_his) + getResources().getString(R.string.br_customer));
                        }else if (getString(R.string.br_supplier).equals(bean.getInviteType())){
                            mContentTitleTv.setText(getString(R.string.user_br_invite_you_become_his)  + getResources().getString(R.string.br_supplier));
                        }
                    } else {
                        ToastUtils.showToast(commonClass.getMsg());
                    }
                    break;
                case 1:
                    if (TextUtils.equals("0", commonClass.getCode())) {
                        BRInviteFriendsSuccessFragment brInviteFriendsSuccessFragment = new BRInviteFriendsSuccessFragment();
                        Bundle bundle = new Bundle();
                        bundle.putString("isAgree",isAgree);
                        bundle.putString("inviterBuName",bean.getInviterBuName());
                        bundle.putString("inviterUserName",bean.getInviterUserName());
                        bundle.putString("inviteType",bean.getInviteType());
                        brInviteFriendsSuccessFragment.setArguments(bundle);
                        pushFragment(brInviteFriendsSuccessFragment);
                    } else {
                        ToastUtils.showToast(commonClass.getMsg());
                    }
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            Log.d(TAG, result);
            ToastUtils.showToast(result);
        }

        @Override
        public void onFinish(int what) {
            dismissProgressDialog();
        }
    };
}
